package com.controller;

import com.alibaba.fastjson.JSONObject;
import com.model._do.UserDO;
import com.model.dto.LoginResultDTO;
import com.model.dto.baseDTO.ResultDTO;
import com.model._do.login_do.LoginFromDO;
import com.model._do.login_do.LoginStatusDO;
import com.model._do.login_do.LoginToDO;
import com.service.ResultService;
import com.service.UserAccessService;
import com.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.logging.Logger;

@RestController
@RequestMapping(value = "/user")
public class UserAccessController {

    @Autowired
    private UserService userService;

    @Autowired
    private ResultService resultService;

    @Autowired
    private UserAccessService userAccessService;

    Logger logger = Logger.getLogger("UserAccessController");

    /**
     * 执行登录动作
     * @param codeDO 发来的wxCode或测试账号标识
     * @param customCode 发来的customCode标识二次登录，绕过微信后台鉴权
     * @return 分配的customCode
     */
    @RequestMapping(value = "/doLogin", method = RequestMethod.POST)
    public ResultDTO doLogin(@RequestBody LoginToDO codeDO, @RequestParam("customCode") String customCode){
        //获取用户的唯一标识
        String openid = null;
        //获取会话秘钥
        String session_key = null;

        logger.info(String.format("customcode is %s",customCode));
        if(customCode.length() > 0) {
            logger.info(String.format("custom codeDO not null, codeDO is %s",customCode));
            LoginStatusDO status = userAccessService.getByCustomCode(customCode);
            if(status != null) {
                openid = status.getOpenId();
            }
        }
        else if(!StringUtils.isEmpty(codeDO.getTest())){
            openid = codeDO.getTestCode();
        }
        else if(codeDO.getCode() == null || codeDO.getCode().length() <= 0){
            return resultService.createFailed(String.format("codeDO is null, request body is :%s", codeDO.toString()));
        }

        if(openid == null) {
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> responseEntity = restTemplate.exchange(codeDO.toString(), HttpMethod.GET, null, String.class);
            if(responseEntity != null && responseEntity.getStatusCode() == HttpStatus.OK){
                logger.info("wx request success\n");
                String sessionData = responseEntity.getBody();
                JSONObject jsonObject = JSONObject.parseObject(sessionData);

                //解析从微信服务器获得的openid和session_key;
                LoginFromDO loginFromDO = new LoginFromDO();
                loginFromDO.setOpenId(jsonObject.getString("openid"));
                loginFromDO.setSessionKey(jsonObject.getString("session_key"));

                //获取用户的唯一标识
                openid = loginFromDO.getOpenId();
                //获取会话秘钥
                session_key = loginFromDO.getSessionKey();
            } else {
                return resultService.createFailed("登录失败，微信服务器不通");
            }
        }

        //user校验并添加
        UserDO user = new UserDO();
        user.setUserId(openid);
        user = userService.saveUser(user);

        /**
         * 进行user 登录状态更新
         */
        LoginStatusDO status = new LoginStatusDO();
        status.setOpenId(openid);
        status.setSessionKey(session_key);

        try{
            customCode = userAccessService.flushByCustomCode(status);
        } catch (Exception e) {
            return resultService.createFailed("登录失败");
        }

        LoginResultDTO loginResult = new LoginResultDTO(customCode, user);
        return resultService.createSuccess("登录成功", loginResult);
    }
}
